<?php

// [ 函数库 ]

if ( !function_exists('p') )
{
    /**
     * [p打印]
     * @param  [type] $val [description]
     * @return [type]      [description]
     */
    function p($val)
    {
        header('Content-Type: text/html; charset=utf-8');
        if ( true === $val || empty($val) ) {
            var_export($val);
        } elseif ( is_array($val) || is_object($val) ) {
            echo '<pre>';
            print_r($val);
            echo '</pre>';
        } else {
            printf($val);
        }
    }
}

if ( !function_exists('f') )
{
    /**
     * [f调试]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    function f($val, $flag = false)
    {
        $fileName = ROOT_PATH . 'runtime' . DS . 'f'. rand(100000,999999) . '.txt';
        $val      = $flag ? json_encode($val,JSON_UNESCAPED_UNICODE) : $val;
        return file_put_contents($fileName,$val);
    }
}

if ( !function_exists('is_mobile') )
{
    /**
     * [判断是否为手机端]
     * @return boolean [description]
     */
    function is_mobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
        {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT']))
        {
            $clientkeywords = array ('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
                );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT']))
        {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                return true;
            }
        }
        return false;
    }
}

if ( !function_exists('mkstr') )
{
    // 获取随机长度的字符串
    // @param  $length 长度 默认32
    // @param  $type   类型 0-大小写字母数字(默认)
    //                      1-大写字母数字
    //                      2-小写字母数字
    //                      3-大小写字母
    //                      4-大写字母
    //                      5-小写字母
    //                      6-数字
    function mkstr($length = 32, $type = 0)
    {
        $digit = '1234567890';
        $upper = 'QWERTYUIOPASDFGHJKLZXCVBNM';
        $lower = 'qwertyuiopasdfghjklzxcvbnm';
        switch ($type) {
            case 0:
                $strPol = $upper . $lower . $digit;
                break;
            case 1:
                $strPol = $upper . $digit;
                break;
            case 2:
                $strPol = $lower . $digit;
                break;
            case 3:
                $strPol = $upper . $lower;
                break;
            case 4:
                $strPol = $upper;
                break;
            case 5:
                $strPol = $lower;
                break;
            case 6:
                $strPol = $digit;
                break;
        }
        $max = strlen($strPol) - 1;
        $str = '';
        for ($i=0; $i<$length; $i++) {
            $str .= $strPol[rand(0,$max)];
        }
        return $str;
    }
}

if ( !function_exists('filter_emoji') )
{
    // 将emoji的unicode置为空，其他不动
    function filter_emoji($str)
    {
        $str = json_encode($str);
        $str = preg_replace("#(\\\ud[0-9a-f]{3})|(\\\ue[0-9a-f]{3})#i","",$str);
        $str = json_decode($str,true);
        return $str;
    }
}

if ( !function_exists('xml_to_array') )
{
    /**
     * XML转换为数组
     * @param  [type] $xml [description]
     * @return [type]      [description]
     */
    function xml_to_array($xml)
    {
        return json_decode( json_encode( simplexml_load_string($xml,'SimpleXMLElement',LIBXML_NOCDATA) ), true );
    }
}

if ( !function_exists('http_curl') )
{
    /**
     * [curl http请求]
     * @param  [type] $url    [description]
     * @param  string $method [description]
     * @param  [type] $data   [description]
     * @return [type]         [description]
     */
    function http_curl($url, $method = 'GET', $data = null)
    {
        $ch = curl_init();
        if ( 'GET' == $method && !empty($data) ) {
            $url .= '?' . http_build_query($data);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if ( in_array($method,['POST','PUT','DELETE']) ) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}

if ( !function_exists('https_curl') )
{
    /**
     * [curl https请求]
     * @param  [type] $url    [description]
     * @param  string $method [description]
     * @param  [type] $data   [description]
     * @return [type]         [description]
     */
    function https_curl($url, $method = 'GET', $data = null)
    {
        $ch = curl_init();
        if ( 'GET' == $method && !empty($data) ) {
            $url .= '?' . http_build_query($data);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        if ( in_array($method,['POST','PUT','DELETE']) ) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}


if ( !function_exists('merge_node') )
{
    /**
     * [递归组合节点]
     * @param  [type]  $node [description]
     * @param  integer $pid  [description]
     * @return [type]        [description]
     */
    function merge_node($node, $pid = 0)
    {
        $arr = array();
        for ($i=0; $i<count($node); $i++) {
            if ($node[$i]['pid'] == $pid) {
                $arr[$i] = $node[$i];
                $arr[$i]['child'] = merge_node($node, $node[$i]['id']);
            }
        }
        $arr = array_merge($arr);
        return $arr;
    }
}
